package com.zhangh.summer.admin.support.utils;

import org.springframework.beans.BeanUtils;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.Date;

/**
 * @description: TODO
 * @author: zhanghui  zhanghlucky@163.com
 * @create: 2021-07-16 22:49
 **/
public class BeanGenerator {
    /**
     * 拷贝
     * @param from 来源对象
     * @param cls 目标对象 class
     * @param <E> 模板对象类型
     * @return 模板对象
     */
    public static <E> E copy(Object from, Class<E> cls){
        E to= null;
        try {
            to = cls.newInstance();
            BeanUtils.copyProperties(from,to);
            fillNull(to);//
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return to;
    }

    /**
     * 拷贝对象属性
     * @param from 来源对象
     * @param to 目标对象
     */
    public static void copy(Object from, Object to){
        BeanUtils.copyProperties(from,to);
    }


    public static  <T>  T create(T t){
        fillNull(t);
        return t;
    }
    public static  <T>  T create(Class<T> cls){
        T t = null;
        try {
            t = cls.newInstance();
            fillNull(t);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return t;
    }

    /**
     * 填充空值
     * @param obj 对象
     */
    public static void fillNull(Object obj){
        try {
            Class cls = obj.getClass();
            Field[] fields = cls.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);

                Object value = field.get(obj);
                String typeName = field.getType().getSimpleName();
                if (null==value){
                    if (typeName.equals(String.class.getSimpleName())) {
                        field.set(obj, "");
                    }
                    if (typeName.equals(Integer.class.getSimpleName())) {
                        field.set(obj, 0);
                    }
                    if (typeName.equals(Long.class.getSimpleName())) {
                        field.set(obj, 0L);
                    }
                    if (typeName.equals(Double.class.getSimpleName())) {
                        field.set(obj, 0.00d);
                    }
                    if (typeName.equals(BigDecimal.class.getSimpleName())) {
                        field.set(obj, BigDecimal.ZERO);
                    }
                    if (typeName.equals(Date.class.getSimpleName())) {
                        field.set(obj, DateUtil.zeroDate());
                    }
                    if (typeName.equals(Boolean.class.getSimpleName())) {
                        field.set(obj, false);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
